from rest_framework.decorators import api_view
from rest_framework import exceptions
from libs.simple_responses import api_success
from libs.decorators import required_data_fields
from system.tasks import deploy as deploy_task
from plugin.services import plugin_service
from system.models import DeployRequest


@api_view(['POST'])
@required_data_fields(['endpoints'])
def deploy(request):
    if plugin_service.exists_processing_plugins():
        raise exceptions.ValidationError({'error': '系统正在安装或卸载插件，请稍后重试'})
    endpoints = request.data.get('endpoints')
    deploy_task.delay(endpoints)
    return api_success()


@api_view(['GET'])
def get_deploy_request(request):
    pending_count = DeployRequest.objects.filter(done=False).count()
    unread_count = DeployRequest.objects.filter(done=False, read=False).count()
    data = {
        'pending': pending_count,
        'unread': unread_count
    }
    DeployRequest.objects.filter(done=False, read=False).update(read=True)
    return api_success(data=data)
